package com.xbongbong.paas.help;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasFormDataEntity;
import com.xbongbong.paas.domain.entity.PaasFormExplainEntity;
import com.xbongbong.paas.domain.entity.PaasStageEntity;
import com.xbongbong.paas.domain.entity.StageLogEntity;
import com.xbongbong.paas.domain.entity.StageWorkLogEntity;
import com.xbongbong.paas.domain.entity.ext.OptionalRangeEntity;
import com.xbongbong.paas.domain.entity.ext.PaasAttachmentEntityExt;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.domain.entity.ext.PaasFormEntityExt;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.field.FilterConditionsPoJo;
import com.xbongbong.paas.field.LinkInfoPojo;
import com.xbongbong.paas.log.MongoLogHelp;
import com.xbongbong.paas.model.PaasFormExplainModel;
import com.xbongbong.paas.model.PaasFormModel;
import com.xbongbong.paas.pojo.StageConditionLintAttrPojo;
import com.xbongbong.paas.pojo.StageConditionPojo;
import com.xbongbong.paas.pojo.StageMessageContentPojo;
import com.xbongbong.paas.service.ProModelService;
import com.xbongbong.paas.service.stage.StageHandle;
import com.xbongbong.paas.service.stage.StageHandleFactory;
import com.xbongbong.paas.service.stage.StageLogHandle;
import com.xbongbong.paas.service.stage.StageLogHandleFactory;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.paas.toolbox.wrap.BaseDTO;
import com.xbongbong.paas.util.ExplainUtil;
import com.xbongbong.paas.util.TitleUtil;
import com.xbongbong.parent.condition.ConditionFieldHandler;
import com.xbongbong.parent.condition.ConditionFieldHandlerFactory;
import com.xbongbong.parent.factory.StageExecuteFactory;
import com.xbongbong.parent.field.FieldAnalyseService;
import com.xbongbong.parent.interfaces.StageExecuteHandle;
import com.xbongbong.parent.util.ConditionUtil;
import com.xbongbong.pro.businessrule.pojo.BusinessRuleInfoPojo;
import com.xbongbong.pro.businesstage.pojo.LogInfoDealPojo;
import com.xbongbong.pro.constant.I18nStringConstant;
import com.xbongbong.pro.enums.SaasMarkEnum;
import com.xbongbong.pro.enums.businessrule.enums.RuleValueTypeEnum;
import com.xbongbong.pro.enums.errorcodes.CustomerStageErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.log.pojo.DetailLogPojo;
import com.xbongbong.pro.thread.ThreadPoolBeanConfig;
import com.xbongbong.saas.domain.entity.StageWorkEntity;
import com.xbongbong.saas.enums.OperateModuleTypeEnum;
import com.xbongbong.saas.enums.OperateTypeEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.ClueEnum;
import com.xbongbong.saas.enums.business.ContractEnum;
import com.xbongbong.saas.enums.business.CustomerManagementEnum;
import com.xbongbong.saas.enums.business.SalesOpportunityEnum;
import com.xbongbong.saas.model.StageWorkModel;
import com.xbongbong.saas.service.UserTeamService;
import com.xbongbong.saas.toolbox.help.FastJsonHelper;
import com.xbongbong.sys.help.SysUserHelp;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

/**
 * @Auther: yingjianfeng
 * @Date: 2021/12/7 20:00
 * @Description:
 */
@Slf4j
@Service("stageDetailHelp")
public class StageDetailHelp {

    @Resource
    private UserTeamService userTeamService;
    @Resource
    private ProModelService proModelService;
    @Resource
    private SysUserHelp sysUserHelp;
    @Resource
    private StageWorkModel stageWorkModel;
    @Resource
    private PaasFormModel paasFormModel;
    @Resource
    private ProFormHelp proFormHelp;
    @Resource
    private StageHandleFactory stageHandleFactory;
    @Resource
    private StageLogHandleFactory stageLogHandleFactory;
    @Resource
    private ThreadPoolBeanConfig threadPoolBeanConfig;
    @Resource
    private MongoLogHelp mongoLogHelp;
    @Resource
    private Map<Integer, FieldAnalyseService> fieldAnalyseMap;
    @Resource
    private PaasFormExplainModel paasFormExplainModel;
    @Resource
    private FormDataHelp formDataHelp;
    @Resource
    private StageExecuteFactory stageExecuteFactory;
    @Resource
    private ConditionFieldHandlerFactory conditionFieldHandlerFactory;

    public Set<String> getUserListByOptionalRange(String corpid, Integer saasMark, Integer businessType, Long dataId, List<OptionalRangeEntity> list) throws XbbException {
        PaasFormDataEntity formDataEntity = proModelService.getFormDataEntity(corpid, saasMark, businessType, dataId);
        String creatorId = formDataEntity.getCreatorId();
        JSONObject jsonObject = formDataEntity.getData();
        //团队
        Map<Long, List<String>> mainUserMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        Map<Long, List<String>> coUserMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        userTeamService.getUserIdMap(Collections.singletonList(dataId), corpid, businessType, false, mainUserMap, coUserMap);
        List<String> mainUserList = mainUserMap.getOrDefault(dataId, new ArrayList<>());
        List<String> coUserList = coUserMap.getOrDefault(dataId, new ArrayList<>());
        jsonObject.put(FieldTypeEnum.OWNERID.getAlias(), mainUserList);
        jsonObject.put(FieldTypeEnum.COUSERID.getAlias(), coUserList);
        return sysUserHelp.getUserListByOptionalRange(corpid, list, jsonObject, creatorId);
    }

    public boolean checkUser(String corpid, Integer saasMark, Integer businessType, Long dataId, JSONArray executor, String userId) throws XbbException {
        List<OptionalRangeEntity> optionalRangeEntityList = JSONObject.parseArray(executor.toJSONString(), OptionalRangeEntity.class);
        Set<String> userListByOptionalRange = getUserListByOptionalRange(corpid, saasMark, businessType, dataId, optionalRangeEntityList);
        return userListByOptionalRange.contains(userId);
    }

    /**
     * description:  重新计算当前阶段的比例
     * * 计算规则： 1.若没有任务 则为跳出比例
     * 2.若有任务，其中一个任务比例不为0，则为进入比例+完成任务比例和
     * * 3.若有任务，任务全部比例全为0，则为跳出比例
     * date: 2021/12/3 9:15 上午
     *
     * @Author yingjf
     */
    public Integer calculateProportion(String corpid, Long formId, Long stageId, Long stageLogId, Integer saasMark, Integer businessType) throws XbbException {
        Map<String, Object> params = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        params.put("id", stageId);
        params.put("corpid", corpid);
        params.put("del", 0);
        StageHandle stageHandle = stageHandleFactory.getStageHandle(saasMark, businessType);
        List<PaasStageEntity> paasStageEntityList = stageHandle.findEntitys(params);
        PaasStageEntity paasStageEntity = paasStageEntityList.get(0);
        Integer intoProportion = paasStageEntity.getIntoProportion();
        Integer outProportion = paasStageEntity.getOutProportion();
        params.clear();
        params.put("corpid", corpid);
        params.put("formId", formId);
        params.put("stageId", stageId);
        params.put("orderByStr", "sort desc");
        params.put("del", 0);
        List<StageWorkEntity> stageWorkEntities = stageWorkModel.findEntitys(params);
        if (CollectionUtils.isEmpty(stageWorkEntities)) {
            return outProportion;
        }
        Map<Long, StageWorkEntity> stageWorkMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        boolean workNoProportion = true;
        for (StageWorkEntity temp : stageWorkEntities) {
            stageWorkMap.put(temp.getId(), temp);
            Integer proportion = temp.getProportion();
            if (proportion != 0) {
                workNoProportion = false;
            }
        }
        // 任务没有比例  则为跳出比例
        if (workNoProportion) {
            return outProportion;
        }
        if (Objects.isNull(stageLogId)) {
            return intoProportion;
        }
        params.clear();
        params.put("corpid", corpid);
        params.put("stageId", stageId);
        params.put("stageLogId", stageLogId);
        params.put("del", 0);
        StageExecuteHandle stageExecuteHandle = stageExecuteFactory.getStageExecute(saasMark, businessType);
        List<StageWorkLogEntity> stageWorkLogEntities = stageExecuteHandle.stageWorkLogFindEntitys(params);
        if (CollectionUtils.isEmpty(stageWorkLogEntities)) {
            return intoProportion;
        }
        Integer workProportion = 0;
        for (StageWorkLogEntity temp : stageWorkLogEntities) {
            // 完成的才加
            if (temp.getIsFinished() == 0) {
                continue;
            }
            Long stageWorkId = temp.getStageWorkId();
            StageWorkEntity stageWorkEntity = stageWorkMap.get(stageWorkId);
            if (Objects.nonNull(stageWorkEntity)) {
                workProportion += stageWorkEntity.getProportion();
            }
        }
        return intoProportion + workProportion;
    }

    /**
     * description:  处理下日志的信息
     * date: 2021/12/23 11:23 上午
     *
     * @Author yingjf
     */
    public LogInfoDealPojo dealLogInfo(String corpid, Long formId, Integer saasMark, Integer businessType, PaasFormDataEntityExt formDataEntity) throws XbbException {
        LogInfoDealPojo logInfoDealPojo = new LogInfoDealPojo();
        String opObjectName;
        OperateModuleTypeEnum operateModuleTypeEnum;
        if (Objects.equals(saasMark, SaasMarkEnum.PAAS.getCode())) {
            PaasFormEntityExt paasFormEntityExt = paasFormModel.getByKey(formId, corpid);
            PaasFormExplainEntity paasFormExplainEntity = proFormHelp.getExplainEntity(corpid, formId, businessType);
            Map<String, FieldAttrEntity> explainMap = ExplainUtil.getExplainMap(paasFormExplainEntity.getExplains(), null);
            opObjectName = TitleUtil.getPaasFormTitle(formDataEntity, paasFormEntityExt, explainMap);
            operateModuleTypeEnum = OperateModuleTypeEnum.PAAS_FORM_DATA;
        } else {
            String attr;
            if (Objects.equals(businessType, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode())) {
                attr = CustomerManagementEnum.NAME.getAttr();
                operateModuleTypeEnum = OperateModuleTypeEnum.CUSTOMER;
            } else if (Objects.equals(businessType, XbbRefTypeEnum.CLUE.getCode())) {
                attr = ClueEnum.COMPANY_NAME.getAttr();
                operateModuleTypeEnum = OperateModuleTypeEnum.CLUE;
            } else if (Objects.equals(businessType, XbbRefTypeEnum.SALES_OPPORTUNITY.getCode())) {
                attr = SalesOpportunityEnum.NAME.getAttr();
                operateModuleTypeEnum = OperateModuleTypeEnum.OPPORTUNITY;
            } else if (Objects.equals(businessType, XbbRefTypeEnum.CONTRACT.getCode())) {
                attr = ContractEnum.NAME.getAttr();
                operateModuleTypeEnum = OperateModuleTypeEnum.CONTRACT;
            } else {
                attr = "text_1";
                operateModuleTypeEnum = OperateModuleTypeEnum.getByAlias(XbbRefTypeEnum.getByCode(businessType).getAlias());
            }
            opObjectName = FastJsonHelper.getStringOrDefaultFromFormData(formDataEntity.getData(), attr, "");
        }
        logInfoDealPojo.setOpObjectName(opObjectName);
        logInfoDealPojo.setOperateModuleTypeEnum(operateModuleTypeEnum);
        return logInfoDealPojo;
    }

    /**
     * description:  评论加日志
     * date: 2021/12/23 11:23 上午
     *
     * @Author yingjf
     */
    public void savaCommentLog(String corpid, Integer saasMark, Integer businessType, Long dataId, BaseDTO baseDTO, Long stageLogId, String oldMsg, String newMsg) throws XbbException {
        StageHandle stageHandle = stageHandleFactory.getStageHandle(saasMark, businessType);
        StageLogHandle stageLogHandle = stageLogHandleFactory.getStageLogHandle(saasMark, businessType);
        if (Objects.isNull(stageHandle) || Objects.isNull(stageLogHandle)) {
            return;
        }
        Runnable runnable = () -> {
            try {
                StageLogEntity stageLogEntity = stageLogHandle.get(stageLogId, corpid);
                Long stageId = stageLogEntity.getStageId();
                PaasStageEntity stageEntity = stageHandle.getByKey(stageId, corpid);
                List<DetailLogPojo> detailArr = new ArrayList();
                PaasFormDataEntityExt formDataEntity = (PaasFormDataEntityExt) proModelService.getFormDataEntity(corpid, saasMark, businessType, dataId);
                Long formId = formDataEntity.getFormId();
                LogInfoDealPojo logInfoDealPojo = dealLogInfo(corpid, formId, saasMark, businessType, formDataEntity);
                String opObjectName = logInfoDealPojo.getOpObjectName();
                OperateModuleTypeEnum operateModuleTypeEnum = logInfoDealPojo.getOperateModuleTypeEnum();
                detailArr.add(new DetailLogPojo(stageEntity.getName() + "-" + I18nMessageUtil.getMessage(I18nStringConstant.STAGE_LOG_SUFFIX_COMMENT),
                        stageEntity.getName() + "-" + I18nMessageUtil.getMessage(I18nStringConstant.STAGE_LOG_SUFFIX_COMMENT), oldMsg, newMsg));
                PaasFormEntityExt paasFormEntityExt = paasFormModel.getByKey(formId, corpid);
                String memo = String.format(I18nMessageUtil.getMessage(I18nStringConstant.STAGE_OPERATION_LOG), baseDTO.getLoginUserName(),
                        paasFormEntityExt.getName(), opObjectName);
                mongoLogHelp.buildLog4DetailArr(detailArr, corpid, baseDTO.getUserId(), baseDTO.getLoginUserName(),
                        operateModuleTypeEnum, OperateTypeEnum.EDIT, formId.toString(), opObjectName, memo, baseDTO.getHttpHeader());
            } catch (Exception e) {
                log.error("评论日志", e);
            }
        };
        threadPoolBeanConfig.addUpdateDelThreadPool().execute(runnable);
    }

    /**
     * description: 消息提示内容
     * date: 2021/12/24 1:44 下午
     *
     * @Author yingjf
     */
    public String getContentValue(List<StageMessageContentPojo> messageContent, Map<Long, Map<String, FieldAttrEntity>> formExplainMap, Map<Long, PaasFormDataEntityExt> paasFormDataEntityExtMap) throws XbbException {
        StringBuilder stringBuilder = new StringBuilder();
        if (CollectionUtils.isEmpty(messageContent)) {
            return stringBuilder.toString();
        }
        for (StageMessageContentPojo pojo : messageContent) {
            //自定义字段
            if (StringUtil.isEmpty(pojo.getAttr())) {
                stringBuilder.append(pojo.getContent());
                continue;
            }
            Long formId = pojo.getFormId();
            Map<String, FieldAttrEntity> explainMap = formExplainMap.get(formId);
            FieldAttrEntity fieldAttrEntity = explainMap.get(pojo.getAttr());
            PaasFormDataEntityExt paasFormDataEntityExt = paasFormDataEntityExtMap.get(formId);
            FieldAnalyseService fieldAnalyseService = fieldAnalyseMap.get(pojo.getFieldType());
            Object value = fieldAnalyseService.analysisData(pojo.getFormId(), pojo.getBusinessType(), pojo.getSaasMark(), paasFormDataEntityExt, paasFormDataEntityExt.getData(), fieldAttrEntity);
            if (Objects.nonNull(value)) {
                stringBuilder.append(value);
            }
        }
        return stringBuilder.toString();
    }

    /**
     * 获取消息内容等信息
     *
     * @return
     * @throws XbbException
     */
    public String getContentValue(List<StageMessageContentPojo> messageContent, Map<String, FieldAttrEntity> explainMap, PaasFormDataEntityExt paasFormDataEntityExt) throws XbbException {
        StringBuilder messageContentBuilder = new StringBuilder();
        if (CollectionUtils.isEmpty(messageContent)) {
            return messageContentBuilder.toString();
        }
        for (StageMessageContentPojo pojo : messageContent) {
            //自定义字段
            if (StringUtil.isEmpty(pojo.getAttr())) {
                messageContentBuilder.append(pojo.getContent());
                continue;
            }
            //查询主表数据
            FieldAttrEntity fieldAttrEntity = explainMap.get(pojo.getAttr());
            FieldAnalyseService fieldAnalyseService = fieldAnalyseMap.get(fieldAttrEntity.getFieldType());
            Object value = fieldAnalyseService.analysisData(pojo.getFormId(), pojo.getBusinessType(), pojo.getSaasMark(), paasFormDataEntityExt, paasFormDataEntityExt.getData(), fieldAttrEntity);
            if (Objects.nonNull(value)) {
                messageContentBuilder.append(value);
            }
        }
        return messageContentBuilder.toString();
    }

    /**
     * description: 校验进入条件   校验是否通过
     *
     * @param corpid       公司id
     * @param dataId       数据id
     * @param saasMark     表单saas标识
     * @param businessType 表单业务类型
     * @param formId       客户，机会，线索，paas表单的表单id
     * @param stageId      即将进入的下一阶段的阶段id
     *                     date: 2021/12/24 3:41 下午
     * @Author yingjf
     */
    public String validateStagePreCondition(String corpid, Integer saasMark, Integer businessType, Long formId, Long dataId, Long stageId) throws XbbException {
        // fix: 2021/12/24    查询都放for外面  注意工单   dataid直接取getlong   不和前端显示一样   待优化
        String contentValue = "";
        boolean validateResult = false;
        // fix 换成 com.xbongbong.paas.help.FormDataHelp.getFormDataEntityExt
        PaasFormDataEntityExt paasFormDataEntity = formDataHelp.getFormDataEntityExt(corpid, saasMark, businessType, dataId);
        JSONObject data = paasFormDataEntity.getData();
        StageHandle stageHandle = stageHandleFactory.getStageHandle(saasMark, businessType);
        PaasStageEntity stageEntity = stageHandle.getByKey(stageId, corpid);
        String preConditions = stageEntity.getPreConditions();
        List<StageConditionPojo> stageConditionPojos = JSON.parseArray(preConditions, StageConditionPojo.class);
        if (CollectionUtils.isEmpty(stageConditionPojos)) {
            return contentValue;
        }
        PaasFormExplainEntity explain = paasFormExplainModel.getByFormId(formId, corpid);
        Map<String, FieldAttrEntity> explainMap = ExplainUtil.getExplainMap(explain.getExplains(), null);
        // 前置拿下数据
        Set<Long> formIdIn = new HashSet();
        Set<Long> workOrderFormIdIn = new HashSet();
        Map<String, Set<Long>> formDataIdMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        // 获取关联表单的表单id，获取关联数据的数据id
        for (StageConditionPojo temp : stageConditionPojos) {
            StageConditionLintAttrPojo linkAttr = temp.getLinkAttr();
            if (Objects.isNull(linkAttr)) {
                return contentValue;
            }
            Long linkDataFormId = linkAttr.getFormId();
            String linkDataAttr = linkAttr.getAttr();
            Integer linkDataSaasMark = linkAttr.getSaasMark();
            Integer linkDataBusinessType = linkAttr.getBusinessType();
            if (Objects.equals(XbbRefTypeEnum.WORK_ORDER.getCode(), linkDataBusinessType)) {
                workOrderFormIdIn.add(linkDataFormId);
            } else {
                formIdIn.add(linkDataFormId);
            }
            if (StringUtil.isNotEmpty(linkDataAttr)) {
                Long linkDataId = data.getLong(linkDataAttr);
                if (linkDataId==null || linkDataId == 0) {
                    if (CollectionUtils.isEmpty(temp.getMessageContent())) {
                        throw new XbbException(CustomerStageErrorCodeEnum.API_ERROR_238052);
                    }
                    // 关联字段未空的情况给提示
                    FieldAttrEntity fieldAttrEntity = explainMap.get(linkDataAttr);
                    throw new XbbException(CustomerStageErrorCodeEnum.API_ERROR_238056, String.format(CustomerStageErrorCodeEnum.API_ERROR_238056.getMsg(), fieldAttrEntity.getAttrName()));
                }
                StringBuffer str = new StringBuffer();
                str.append(linkDataBusinessType).append("-").append(linkDataSaasMark).append("-").append(linkDataFormId);
                String formDataIdMapKey = str.toString();
                Set<Long> ids = formDataIdMap.get(formDataIdMapKey);
                if (CollectionUtils.isEmpty(ids)) {
                    Set<Long> set = new HashSet<>();
                    set.add(linkDataId);
                    formDataIdMap.put(formDataIdMapKey, set);
                } else {
                    ids.add(linkDataId);
                }
            }
        }
        for (String temp : explainMap.keySet()) {
            FieldAttrEntity fieldAttrEntity = explainMap.get(temp);
            LinkInfoPojo linkInfo = fieldAttrEntity.getLinkInfo();
            Integer fieldType = fieldAttrEntity.getFieldType();
            Long linkDataId = null;
            if (Objects.equals(fieldType, FieldTypeEnum.LINK_DATA.getType())) {
                linkDataId = data.getLong(temp);
            } else {
                continue;
            }
            StringBuffer str = new StringBuffer();
            str.append(linkInfo.getLinkBusinessType()).append("-").append(linkInfo.getLinkSaasMark()).append("-").append(linkInfo.getLinkFormId());
            String formDataIdMapKey = str.toString();
            Set<Long> ids = formDataIdMap.get(formDataIdMapKey);
            if (CollectionUtils.isEmpty(ids)) {
                Set<Long> set = new HashSet<>();
                set.add(linkDataId);
                formDataIdMap.put(formDataIdMapKey, set);
            } else {
                ids.add(linkDataId);
            }
        }

        Map<String, PaasFormDataEntityExt> formDataMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        Set<String> keySet = formDataIdMap.keySet();
        // 遍历获取工单和非工单的数据集合
        for (String temp : keySet) {
            Set<Long> ids = formDataIdMap.get(temp);
            String[] strings = temp.split("-");
            Integer linkDataBusinessType = Integer.parseInt(strings[0]);
            Integer linkDataSaasMark = Integer.parseInt(strings[1]);
            Long linkDataFormId = Long.parseLong(strings[2]);
            List<PaasFormDataEntityExt> paasFormDataEntityExtList = formDataHelp.getByDataIdList(ids, linkDataBusinessType, linkDataSaasMark, linkDataFormId, corpid);
            // 解出来 拼上id 下面方便直接取
            for (PaasFormDataEntityExt tempData : paasFormDataEntityExtList) {
                Long id = tempData.getId();
                StringBuffer stringBuffer = new StringBuffer();
                stringBuffer.append(linkDataBusinessType).append("_").append(id);
                formDataMap.put(stringBuffer.toString(), tempData);
            }
        }
        Map<Long, Map<String, FieldAttrEntity>> formFieldMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        formFieldMap = proFormHelp.getFormFieldMap(formIdIn, corpid);
        Map<Long, Map<String, FieldAttrEntity>> workOrderFormFieldMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        workOrderFormFieldMap = proFormHelp.getWorkOrderFormFieldMap(workOrderFormIdIn, corpid);
        for (StageConditionPojo temp : stageConditionPojos) {
            StageConditionLintAttrPojo linkAttr = temp.getLinkAttr();
            Long linkDataFormId = linkAttr.getFormId();
            String linkDataAttr = linkAttr.getAttr();
            Integer linkDataSaasMark = linkAttr.getSaasMark();
            Integer linkDataBusinessType = linkAttr.getBusinessType();
            List<StageMessageContentPojo> messageContent = temp.getMessageContent();
            List<FilterConditionsPoJo> preConditionList = temp.getFilter();
            Map<String, FieldAttrEntity> targetExplainMap = null;
            if (Objects.equals(XbbRefTypeEnum.WORK_ORDER.getCode(), linkDataBusinessType)) {
                targetExplainMap = workOrderFormFieldMap.get(linkDataFormId);
            } else {
                targetExplainMap = formFieldMap.get(linkDataFormId);
            }
            BusinessRuleInfoPojo businessRuleInfoPojo = new BusinessRuleInfoPojo(formId, corpid, businessType, targetExplainMap, formDataMap);
            try {
                for (FilterConditionsPoJo item : preConditionList) {
                    // 本表
                    if (linkAttr.getType() == 1) {
                        FieldAttrEntity fieldAttrEntity = explainMap.get(item.getAttr());
                        if (Objects.isNull(fieldAttrEntity)) {
                            // 字段被删除的情况
                            break;
                        }
                        ConditionFieldHandler conditionFieldHandler = conditionFieldHandlerFactory.handlerPreConditionByFieldType(item.getFieldType());
                        Object object = conditionFieldHandler.handlerPreConditionValue(fieldAttrEntity, businessRuleInfoPojo, item);
                        validateResult = SymbolHelp.handleSymbol(object, paasFormDataEntity, item, fieldAttrEntity);
                        if (!validateResult) {
                            if (CollectionUtils.isEmpty(messageContent)) {
                                throw new XbbException(CustomerStageErrorCodeEnum.API_ERROR_238052);
                            }
                            Map<Long, Map<String, FieldAttrEntity>> formExplainMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                            formExplainMap.put(formId, explainMap);
                            Map<Long, PaasFormDataEntityExt> paasFormDataEntityExtMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                            paasFormDataEntityExtMap.put(formId, paasFormDataEntity);
                            contentValue = getContentValue(messageContent, formExplainMap, paasFormDataEntityExtMap);
                            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, contentValue);
                        }
                    } else {
                        // 关联表
                        if (Objects.isNull(linkDataAttr)) {
                            // 关联字段被删除的情况
                            break;
                        }
                        Long linkDataId = data.getLong(linkDataAttr);
                        StringBuffer stringBuffer = new StringBuffer();
                        stringBuffer.append(linkDataBusinessType).append("_").append(linkDataId);
                        PaasFormDataEntityExt linkPaasFormDataEntity = formDataMap.get(stringBuffer.toString());
                        if (Objects.equals(item.getValueType(), RuleValueTypeEnum.DYNAMIC_VALUE.getType())) {
                            FieldAttrEntity fieldAttrEntity = explainMap.get(item.getValueAttr());
                            FieldAttrEntity targetField = targetExplainMap.get(item.getAttr());
                            // 关联表
                            if (Objects.isNull(fieldAttrEntity) || Objects.isNull(targetField)) {
                                // 字段被删除的情况
                                break;
                            }
                            // 处理下动态的
                            // 获取目标表单数据
                            BusinessRuleInfoPojo targetBusinessRuleInfoPojo = new BusinessRuleInfoPojo(linkDataFormId, corpid, linkDataBusinessType, explainMap, formDataMap);
                            ConditionFieldHandler conditionFieldHandler = conditionFieldHandlerFactory.getHandlerByFieldType(item.getFieldType());
                            Object targetValue = conditionFieldHandler.handlerThisFormField(linkPaasFormDataEntity, linkPaasFormDataEntity.getData(), targetField, fieldAttrEntity, targetBusinessRuleInfoPojo);
                            // 获取本表单数据
                            ConditionFieldHandler thisConditionFieldHandler = conditionFieldHandlerFactory.getHandlerByFieldType(fieldAttrEntity.getFieldType());
                            Object object = thisConditionFieldHandler.handlerThisFormField(paasFormDataEntity, paasFormDataEntity.getData(), fieldAttrEntity, targetField, businessRuleInfoPojo);
                            validateResult = ConditionUtil.equals(targetValue, object, item);
                        } else {
                            FieldAttrEntity fieldAttrEntity = targetExplainMap.get(item.getAttr());
                            if (Objects.isNull(fieldAttrEntity)) {
                                // 字段被删除的情况
                                break;
                            }
                            // 处理下固定的
                            ConditionFieldHandler conditionFieldHandler = conditionFieldHandlerFactory.handlerPreConditionByFieldType(item.getFieldType());
                            Object object = conditionFieldHandler.handlerPreConditionValue(fieldAttrEntity, businessRuleInfoPojo, item);
                            validateResult = SymbolHelp.handleSymbol(object, paasFormDataEntity, item, fieldAttrEntity);
                        }
                        if (!validateResult) {
                            if (CollectionUtils.isEmpty(messageContent)) {
                                throw new XbbException(CustomerStageErrorCodeEnum.API_ERROR_238052);
                            }
                            Map<Long, Map<String, FieldAttrEntity>> formExplainMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                            formExplainMap.put(linkDataFormId, targetExplainMap);
                            Map<Long, PaasFormDataEntityExt> paasFormDataEntityExtMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                            paasFormDataEntityExtMap.put(linkDataFormId, linkPaasFormDataEntity);
                            contentValue = getContentValue(messageContent, formExplainMap, paasFormDataEntityExtMap);
                            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, contentValue);
                        }
                    }
                }
            } catch (XbbException e) {
                throw e;
            } catch (Exception e) {
                log.error("com.xbongbong.paas.help.StageDetailHelp.validateStagePreCondition ", e);
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
            }
        }
        return contentValue;
    }

    /**
     * 获取 图片回参
     * @param imagePojoStr
     * @return
     */
    public static List<String> getImageHtmlList(String imagePojoStr) {
        List<String> res = new ArrayList<>();
        if (StringUtil.isEmpty(imagePojoStr)) {
            return res;
        }
        try {
            List<PaasAttachmentEntityExt> paasAttachmentEntityExts = JSONArray.parseArray(imagePojoStr, PaasAttachmentEntityExt.class);
            for (PaasAttachmentEntityExt paasAttachmentEntityExt : paasAttachmentEntityExts) {
                res.add(paasAttachmentEntityExt.getAttachIndex());
            }
        } catch (JSONException e) {
            //老数据更新
            List<String> oldImageData = JSONArray.parseArray(imagePojoStr, String.class);
            res.addAll(oldImageData);
        } catch (Exception e) {
            log.info("StageDetailHelp.getImageHtmlList", e);
        }
        return res;
    }
}
